package com.frxuexi.shop2307.user

import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.text.Editable
import android.text.TextWatcher
import android.util.Log
import com.alibaba.android.arouter.facade.annotation.Route
import com.alibaba.android.arouter.launcher.ARouter
import com.blankj.utilcode.util.SPUtils
import com.blankj.utilcode.util.ToastUtils
import com.frxuexi.lib_base.http.Const
import com.frxuexi.lib_base.mvvm.BaseActivity
import com.frxuexi.shop2307.R
import com.frxuexi.shop2307.databinding.ActivityCodeBinding
import dagger.hilt.android.AndroidEntryPoint

@AndroidEntryPoint
class CodeActivity : BaseActivity<ActivityCodeBinding,UserViewModel>() {
    override fun initData() {
        vm.loginData.observe(this){
            Log.i("lr",it.toString())
            ToastUtils.showLong("登录成功")
            SPUtils.getInstance().put(Const.TOKEN,it.token)
            SPUtils.getInstance().put(Const.PHONE,it.phone)

            vm.loginRoom(it)

        }

        vm.loginError.observe(this){
            ToastUtils.showLong(it)
        }

        vm.loginRoomData.observe(this){
            if(it>0){
                Log.i("lr","room新增user成功${it}")
                ARouter.getInstance().build("/app/MainActivity").navigation()
                finish()
            }
        }

    }

    override fun initView() {
        val bundle = intent.extras
        val phone = bundle?.getString("phone")!!
        val code = bundle?.getInt("code").toString()

        binding.codePhone.append(phone.replace(phone.substring(3,7),"****"))

        ToastUtils.showLong("${phone},${code}")

        binding.codeBack.setOnClickListener {
            finish()
        }

        binding.codeSix.addTextChangedListener(object :TextWatcher{
            override fun beforeTextChanged(s: CharSequence?, start: Int, count: Int, after: Int) {

            }

            override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) {
                if(s?.length==1){
                    val one = binding.codeOne.text.toString()
                    val two = binding.codeTwo.text.toString()
                    val three = binding.codeThree.text.toString()
                    val four = binding.codeFour.text.toString()
                    val five = binding.codeFive.text.toString()
                    if(one.isNullOrEmpty() || two.isNullOrEmpty()|| three.isNullOrEmpty()|| four.isNullOrEmpty()|| five.isNullOrEmpty()){
                        ToastUtils.showLong("请输入完整验证码")
                        return
                    }
                    val mycode = one.plus(two).plus(three).plus(four).plus(five).plus(s.toString())
                    vm.login(mapOf<String, Any>("phone" to phone, "captcha" to mycode))
                }
            }

            override fun afterTextChanged(s: Editable?) {
            }

        })

    }

}